#!/bin/bash
# 将打包后的素材上传到 Nexus 服务器

projectName="app"

nexusapppubIp="apppub.linkdood.cn:8081"

error() {
  echo -e "\033[31m[error] $1\033[0m"
}

warning() {
  echo -e "\033[33m$1\033[0m"
}

info() {
  echo -e "\033[32m$1\033[0m"
}

# 检查命令是否存在
checkCmd() {
  ret=0

  if ! hash curl 2>/dev/null; then
    error "curl not found"
    ret=1
  fi

  if [ $ret -ne 0 ]; then
    exit 1
  fi
}

usage() {
    echo "Usage: $0 [nexus ip]　[repo] [version]"
    echo ""
    echo "nexus ip:"
    echo "  apppub : equal to $nexusapppubIp"
    echo ""
    echo "repo:"
    echo "  d : develop"
    echo "  y : yingyong"
    echo "  shu : shuguang 曙光"
    echo ""
    echo "Example:"
    echo "  $0 apppub d v3.3.0"
}

upload() {
  deployFile="${projectName}-deploy.tgz"
  if [[ ! -f $deployFile ]]; then
    error "can not found $deployFile"
    exit 1
  fi

  info "upload $deployFile to $1"

  curl -v --user "admin:admin123" --upload-file ${deployFile} $1/${deployFile}

  # curl 有可能会执行失败，需要手动检查下服务器上已经更新成功
  info "Upload finish, please check file uploaded"
}

if [[ $# -ne 3 ]]; then
    usage
    exit 1
fi

checkCmd

if [[ "$1" == "apppub" ]]; then
  nexusIp=${nexusapppubIp}
else
  error "$1 is not a valid nexus server ip."
  exit 1
fi

if [[ "$2" == "d" ]]; then
  repo="develop"
elif [[ "$2" == "y" ]]; then
  repo="yingyong"
elif [[ "$2" == "shu" ]]; then
  repo="shuguang"
else
  error "$2 is not a valid repo name."
  exit 1
fi

echo "$3" | grep 'v' >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
  error "$3 is not a valid version."
  exit 1
fi

url="http://${nexusIp}/repository/"${repo}"/${projectName}/$3"

upload $url
